package com.guoxin.jiyin.boot;

import com.alibaba.fastjson.JSON;
import com.guoxin.jiyin.enums.ApiCode;
import com.guoxin.jiyin.model.ApiResult;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.DigestUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.TreeMap;

public class ApiHandlerInterceptor implements HandlerInterceptor {
    private Logger logger = LogManager.getLogger(ApiHandlerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        logger.info(request.getRequestURI());

        String sign = request.getParameter("sign");
//        logger.info("sign:" + getSign(request));
        if (sign == null || !sign.equals(getSign(request))) {
            ApiResult result = new ApiResult();
            result.setCode(ApiCode.REQUEST_ERROR.getValue());
            result.setMessage(ApiCode.REQUEST_ERROR.getName());
            PrintWriter out = null;
            try {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                out = response.getWriter();
                out.append(JSON.toJSONString(result));
            } finally {
                if (out != null) {
                    out.close();
                }
            }
            logger.info("fail");
            return false;
        }

        logger.info("pass");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    private String getSign(HttpServletRequest request) throws UnsupportedEncodingException {
        Map<String, String> resultMap = new TreeMap<>();
        Map map = request.getParameterMap();
        for (Object key : map.keySet()) {
            resultMap.put(key.toString(), request.getParameter(key.toString()));
        }
        StringBuilder strB = new StringBuilder();
        resultMap.keySet().stream().filter(key -> !"sign".equals(key)).forEach(key -> strB.append(key + resultMap.get(key)));
        strB.append("4165a8d240b29af3f41818d10599d0d1");
//        System.out.println(strB.toString() );

        return DigestUtils.md5DigestAsHex(strB.toString().getBytes("UTF-8")).toLowerCase();
    }

}
